import time
import nmap3
from IPy import IP


###行为整合。去掉IP网段重的网络号与广播地址，并对检测动作与生成日志进行整合
def behavior(subnet):
    ip_list = IP(subnet)
    for hostip in ip_list[1:-1]:
        result = ping_scan(hostip)
        log(result)


###检测动作。判断IP是否存活（检测机制是以能否ping通为准），并输出对应ip存活信息
def ping_scan(ip):
    nmap = nmap3.NmapScanTechniques()
    if bool(nmap.nmap_ping_scan(ip)):
        return '{} up\n'.format(ip)
    else:
        return '{} down\n'.format(ip)


###生成日志。将对应IP存活信息进行收录，日志文件名称为任务执行时间
def log(result):
    global time_now_all
    log_name = time_now_all + ".log"
    with open(log_name, 'a+') as scan_result:
        scan_result.write(result)


###任务执行时间点
def job_time():
    jobtime = ['00:00:00',
               '01:00:00',
               '02:00:00',
               '03:00:00',
               '04:00:00',
               '05:00:00',
               '06:00:00',
               '07:00:00',
               '08:00:00',
               '09:00:00',
               '10:00:00',
               '11:00:00',
               '12:00:00',
               '13:00:00',
               '14:00:00',
               '15:00:00',
               '16:00:00',
               '17:00:00',
               '18:00:00',
               '19:00:00',
               '20:00:00',
               '21:00:00',
               '22:00:00',
               '23:00:00',
               '09:30:00',
               '10:30:00',
               '11:30:00',
               '12:30:00',
               '13:30:00',
               '14:30:00',
               '15:30:00',
               '16:30:00',
               '17:30:00',
               '18:30:00',
               '19:30:00'
               ]
    return jobtime


###IP地址输入，输出对应IP网段
def subnet_in():
    subnetip = input('请输入ip地址和掩码长度（格式：192.168.1.1/24）：\n')
    subnet = IP(subnetip, make_net=True)
    return subnet


if __name__ == '__main__':
    subnet = subnet_in()
    while True:
        time_now_hm = time.strftime("%H:%M:%S", time.localtime())
        time_now_all = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
        print(time_now_all)
        jobtime = job_time()
        if time_now_hm in jobtime:
            behavior(subnet)
        time.sleep(1)